// pages/my/my.js
const wxaUserService = require('../../../../api/wxaUserService.js')
const memberService = require('../../../../api/memberService.js')
const auth = require('../../../../utils/auth.js')
const utils = require('../../../../utils/utils.js')

//获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    genders: [{
      name: '先生',
      value: 'MALE',
      id: 0
    }, {
      name: '女士',
      value: 'FEMALE',
      id: 1
    }],
    userGenders: -1,
    userInfo: {},
    member: {},
    picker_switch: false,
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    date: '未填写',
    endDate: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu()
    const that = this
    if (app.globalData.userInfo) {
      if (app.globalData.userInfo.member) {
        const member = app.globalData.userInfo.member
        const wxaUser = app.globalData.userInfo.wxaUser
        console.log(member)
        this.setData({
          userInfo: {
            ...wxaUser,
            nickName: member.nickName ? member.nickName : wxaUser.nickName
          },
          hasUserInfo: true,
          memberTel: that.hideTel(member.mobile),
          nickName: member.nickName,
          gradeName: member.gradeName,
          member: member
        })
        if (member.birthday) {
          this.setData({
            date: member.birthday,
            //现在业务中，生日一旦设置就不可更改
            picker_switch: true
          })
        } else {
          let date = new Date()
          let now = utils.formatTime(date)
          let newTime = now.replace(/\//g, '-')
          let data = newTime.split(' ')[0]
          this.setData({
            endDate: data,
          })
        }
        if (member.gender === "UNKNOWN") {
          this.setData({
            userGenders: -1
          })
        } else if (member.gender === "MALE") {
          this.setData({
            userGenders: 0
          })
        } else if (member.gender === "FEMALE") {
          this.setData({
            userGenders: 1
          })
        }
      } else {
        // 不是会员
        this.setData({
          hasUserInfo: false
        })
      }
    } else {
      // 未登录
    }
  },

  genderClick: function (e) {
    const that = this
    var index = e.currentTarget.dataset.index;
    if (that.data.userGenders !== index) {
      that.setData({
        userGenders: index
      })
    } else {
      that.setData({
        userGenders: -1
      })
    }
  },

  getUserInfo: function (e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    wx.setStorage({
      key: "wj_userInfo",
      data: e.detail.userInfo
    })
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
    wxaUserService.login().then(res => {
      console.log(res)
      auth.setUser(res)
      app.globalData.userInfo = res
      if (!res.member) {
        this.setData({
          isMember: false
        })
        wx.navigateTo({
          url: '../bindMobile/bindMobile'
        })
      } else {
        this.setData({
          member: res.member,
          isMember: true
        })
        wx.setStorage({
          key: "wj_member",
          data: res.member
        })
      }
    }).catch(err => {
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
    });
  },
  // 手机号隐藏中间四位
  hideTel: function (tel) {
    var reg = /^(\d{3})\d{4}(\d{4})$/;
    tel = tel.replace(reg, "$1****$2");
    return tel
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  // 昵称输入
  inputNiceName: function (e) {
    console.log(e.detail)
    this.setData({
      nickName: e.detail.value
    })
    if (e.detail.cursor > 10) {
      wx.showToast({
        title: '昵称最大不能超过10个字符哦~',
        icon: 'none',
        duration: 2000
      })
    }
  },

  //生日选择
  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value
    })
  },

  handleSave: function (e) {
    console.log(e.detail.value)
    var self = this;
    if (!e.detail.value.nickName) {
      wx.showToast({
        title: "请填写昵称",
        icon: 'none',
        duration: 2000
      })
    } else if (!e.detail.value.date || e.detail.value.date === '未填写') {
      wx.showToast({
        title: "请选择生日",
        icon: 'none',
        duration: 2000
      })
    } else {
      //调起接口
      var memberInfo = app.globalData.userInfo.member
      let postData = {
        id: memberInfo.id,
        nickName: e.detail.value.nickName,
        birthday: e.detail.value.date + " 00:00:00",
      }
      if (self.data.userGenders === -1) {
        memberInfo.gender = 'UNKNOWN'
        postData = {
          ...postData,
          gender: 'UNKNOWN'
        }
      } else if (self.data.userGenders === 0) {
        memberInfo.gender = 'MALE'
        postData = {
          ...postData,
          gender: 'MALE'
        }
      } else if (self.data.userGenders === 1) {
        memberInfo.gender = 'FEMALE'
        postData = {
          ...postData,
          gender: 'FEMALE'
        }
      }

      console.log(postData)
      if (postData.id !== null && postData.id !== undefined) {
        memberService.update(postData).then(res => {
          console.log(res)
          utils.setHideLoading(true)
        }).then(res => {
          wxaUserService.login().then(res => {
            console.log(res)
            utils.setHideLoading(false)
            auth.setUser(res)
            app.globalData.userInfo = res
            if (res.member) {
              wx.setStorage({
                key: "wj_member",
                data: res.member
              })
            } else {

            }
            wx.navigateBack({
              delta: 1
            })
          }).catch(err => {
            wx.showToast({
              title: err.message,
              icon: 'none',
              duration: 2000
            })
            wx.navigateBack({
              delta: 1
            })
          });
        }).catch(err => {
          wx.showToast({
            title: err.message,
            icon: 'none',
            duration: 2000
          })
        })
      } else {
        wx.showToast({
          title: '您还不是会员，请绑定手机号成为会员~',
          icon: 'none',
          duration: 2000
        })
      }
    }
  }
})